package com.github.data_manage.common

import com.github.data_manage.util.mapAsyncBlocking
import org.springframework.data.domain.Page


/**
 * 分页数据封装类
 * Created by macro on 2019/4/19.
 */
class CommonPage<T> {
    var pageNum: Long? = null
    var pageSize: Long? = null
    var totalPage: Long? = null
    var total: Long? = null
    var list: List<T>? = null

    companion object {
        /**
         * 将MyBatis Plus 分页结果转化为通用结果
         */
        fun <T> restPage(pageResult: Page<T>): CommonPage<T> {
            val result = CommonPage<T>()
            result.pageNum = pageResult.number.toLong()
            result.pageSize = pageResult.size.toLong()
            result.total = pageResult.totalElements
            result.totalPage = pageResult.totalPages.toLong()
            result.list = pageResult.content
            return result
        }

        fun <T> empty(
            pageNum: Long,
            pageSize: Long): CommonPage<T> {
            val result = CommonPage<T>()
            result.pageNum = pageNum
            result.pageSize = pageSize
            result.total = 0
            result.totalPage = 0
            result.list = emptyList()
            return result
        }
    }

    fun <R> map(mapper: (T) -> R): CommonPage<R> {
        val result = CommonPage<R>()
        result.pageNum = pageNum
        result.pageSize = pageSize
        result.total = total
        result.totalPage = totalPage
        result.list = list?.map { mapper(it) }
        return result
    }

    fun <R> mapAsync(mapper: (T) -> R): CommonPage<R> {
        val result = CommonPage<R>()
        result.pageNum = pageNum
        result.pageSize = pageSize
        result.total = total
        result.totalPage = totalPage
        result.list = list?.mapAsyncBlocking { mapper(it) }
        return result
    }
}
